package com.juzipi.demo.filter;

import com.juzipi.demo.pojo.User;
import com.juzipi.demo.service.RoleService;
import com.juzipi.demo.service.TokenService;
import com.juzipi.demo.service.UserRoleService;
import com.juzipi.demo.service.UserService;
import com.juzipi.demo.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token验证过滤器
 */

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;


    //内部过滤
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String tokenStr = httpServletRequest.getHeader("token");
        if (StringUtils.isNotBlank(tokenStr)){
            //验证token
            boolean verify = JwtUtil.verify(tokenStr);
            if (verify){
                //验证通过就获取用户的信息
                User user = JwtUtil.getAuthentication(tokenStr);
                if (user != null){
                    //不懂具体，用户名密码身份验证令牌？
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    //初版
    /*@Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String tokenStr = httpServletRequest.getHeader("token");
        if (StringUtils.isNotBlank(tokenStr)){
            //token不为空就根据此token查询数据库中的token
            Token tokenDb = tokenService.queryToken(tokenStr);
            if (tokenDb != null && tokenDb.getUserId() != null){
                //如果token不为空且token里的userid不为空就根据userid查询用户
                User user = userService.queryUserById(tokenDb.getUserId());
                if (user == null){
                    throw new UsernameNotFoundException("token已失效");
                }
                //根据查询出的用户id去查询UserRole中间表
                List<UserRole> userRoles = userRoleService.queryUserRoleList(user.getId());
                if (userRoles != null && !userRoles.isEmpty()){
//                        ArrayList<Long> roleIds = new ArrayList<>();
//                        for (UserRole list: userRoles){
//                            roleIds.add(list.getRoleId());
//                        }
//                        //根据用户角色的id集合获取角色集合
//                        List<Role> roles = roleService.queryRoleList(roleIds);
//                        user.setRoleList(roles);
                    //应该就是上面的操作简写了，学学，不试试永远不会
                    List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
                    List<Role> roles = roleService.queryRoleList(roleIds);
                    user.setRoleList(roles);
                }
                user.setToken(tokenStr);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                System.out.printf("打印一下%n",user.getUsername());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }*/
}
